
class Wordwriting {

    constructor() 
    { 

    }

    start(label, words, delta, callback) 
    {
        this.stop()

        if (!label || !words) return false

        this.mSpeedCount = 1

        if (delta <= 0) 
        {

            label.getComponent(cc.Label).string = words

            callback && callback()

        } 
        else 
        {
            this.mWordSize = words.length

            if (this.mWordSize <= 0) return false

            this.mWord          = words
            this.mLabel         = label

            this.mWritingSpeed  = delta
            this.mTimer         = this.mWritingSpeed
            this.mWritingIndex  = 0

            this.mEndCallback = callback

            this.write(0)
        }

        return true
    }

    stop() 
    {
        this.mLabel         = null

        this.mEndCallback   = null

        this.mSpeedCount    = 1
    }

    update(dt) 
    {    
        if (!this.mLabel) return

        if (this.mSpeedCount > 0) 
        {
            this.mTimer = this.mTimer + dt * this.mSpeedCount

            let to = Math.floor(this.mTimer / this.mWritingSpeed)

            this.write(to)
        } 
        else 
        {    
            this.write(this.mWordSize)
        }
    }

    write(to) 
    {
        if (this.mLabel) 
        {
            if(!this.mWritingIndex || to > this.mWritingIndex) 
            {
                this.mWritingIndex = to

                if (to >= this.mWordSize) 
                {
                    this.mLabel.getComponent(cc.Label).string = this.mWord

                    this.mEndCallback && this.mEndCallback()

                    this.stop()
                } 
                else 
                {
                    this.mLabel.getComponent(cc.Label).string = this.mWord.substring(0, to)
                }
            }
        }
    }

    isWriting() 
    {
        return this.mLabel != null
    }

    speedup(max) 
    {
        if (!this.mLabel) return

        if (max > 0) 
        {
            if (this.mSpeedCount < max) this.mSpeedCount += 1
        } 
        else 
        {
            this.mSpeedCount = 0
        }
    }
}

export default Wordwriting
